package cn.hpclub.server.controller.client.recommend;

import java.util.Date;
import java.util.Map;

import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Record;

import cn.hpclub.server.constant.ClientApiConstant;
import cn.hpclub.server.controller.client.BaseClientController;
import cn.hpclub.server.model.MemberOrg;
import cn.hpclub.server.model.recommend.Recommend;
import cn.hpclub.server.restful.API;
import cn.hpclub.server.service.recommend.RecommendService;
import cn.hpclub.server.util.InterfaceUtil;
import cn.hpclub.server.util.ObjectUtil;

@API("/recommend/client")
public class RecommendClientController extends BaseClientController<Recommend>{

    private static Logger logger = LoggerFactory.getLogger(RecommendClientController.class);

    /**
     * 客户端获取用户推荐关系相关数据接口
     */
    public void getRecommendInfo(){
        JSONObject jsonObject = setResponseObj(ClientApiConstant.ResultCode.FAILED, ClientApiConstant.Msg.FAIL,
                                               ClientApiConstant.Msg.EMPTY);
        String token = getPara(ClientApiConstant.Key.TOKEN);
        Record userInfoRecord = InterfaceUtil.getuserInfoByToken(token);
        int user_id = userInfoRecord.getInt("id");
        Map<String, Object> map = RecommendService.service.getRecommendInfo(user_id);
        jsonObject = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, ClientApiConstant.Msg.SUCCESS, map);
        renderJson(jsonObject.toString());
    }

    /**
     * 新用户建立推荐关系数据保存接口
     */
    public void saveRecommendInfo(){
        JSONObject jsonObject = setResponseObj(ClientApiConstant.ResultCode.FAILED, ClientApiConstant.Msg.FAIL,
                                               ClientApiConstant.Msg.EMPTY);
        Recommend recommend = new Recommend();
        try{
            String recommender_phone = getPara(Recommend.RECOMMENDER_PHONE, null);
            String token = getPara(ClientApiConstant.Key.TOKEN);
            MemberOrg memberOrg = validateParameter(recommender_phone, token);

            recommend.set(Recommend.USER_ID, memberOrg.get(MemberOrg.ID, null));
            recommend.set(Recommend.NAME, memberOrg.get(MemberOrg.NAME, null));
            recommend.set(Recommend.PHONE, memberOrg.get(MemberOrg.USER_NAME, null));
            recommend.set(Recommend.RECOMMENDER_PHONE, recommender_phone);
            recommend.set(Recommend.CREATE_TIME, new Date());
            if(recommend.save()){
                String id = String.valueOf(recommend.getInt(Recommend.ID));
                logger.debug("save recommend info success,primary Id=" + id);
                jsonObject = setResponseObj(ClientApiConstant.ResultCode.SUCCESS_CODE, "save recommend info success",
                                            ClientApiConstant.Msg.EMPTY);
            }
        }
        catch(IllegalArgumentException e){
            logger.error("save recommend info failed,error message:" + e.getMessage());
            jsonObject = setResponseObj(ClientApiConstant.ResultCode.PARAM_ERROR, e.getMessage(),
                                        ClientApiConstant.Msg.EMPTY);
        }
        catch(Exception e){
            logger.error("save recommend info failed,error message:" + e.getMessage());
            jsonObject = setResponseObj(ClientApiConstant.ResultCode.SERVER_EXCEPTION, "服务器错误",
                                        ClientApiConstant.Msg.EMPTY);
        }
        renderJson(jsonObject.toString());
    }

    /**
     * 参数合法性校验
     * 
     * @param recommender_phone
     * @return
     * @throws IllegalArgumentException
     */
    private MemberOrg validateParameter(String recommender_phone, String token) throws IllegalArgumentException{
        if(StrKit.isBlank(token)){
            throw new IllegalArgumentException("token不合法");
        }
        Record userInfoRecord = InterfaceUtil.getuserInfoByToken(token);
        int user_id = userInfoRecord.getInt("id");
        if(StrKit.isBlank(recommender_phone)){
            throw new IllegalArgumentException("推荐人手机号不能为空");
        }
        if(user_id == -1){
            throw new IllegalArgumentException("用户Id不能为空");
        }
        Record record = RecommendService.service.getMemberOrgByPhone(recommender_phone);
        if(ObjectUtil.isEmpty(record)){// 判断用户输入的推荐人手机号码是否在系统中存在
            logger.error("recommender is not exist in database table 'member_org',parameter user_name is "
                    + recommender_phone);
            throw new IllegalArgumentException("推荐人手机号不合法");
        }
        MemberOrg memberOrg = MemberOrg.dao.findById(user_id);
        if(ObjectUtil.isEmpty(memberOrg)){// 判断客户端请求的用户id是否合法
            logger.error("memberOrg is not exist in database table 'member_org',primary key  is " + user_id);
            throw new IllegalArgumentException("用户登录错误");
        }
        if(recommender_phone.equals(memberOrg.getStr("user_name"))){// 判断用户输入的推荐人电话是否为用户自己
            logger.error("recommender_phone can't be equal to oneself");
            throw new IllegalArgumentException("推荐人不能是自己");
        }
        Recommend recommend = Recommend.dao.findFirst("select * from recommend where user_id=?", user_id);
        if(ObjectUtil.isNotEmpty(recommend)){// 判断用户是否重复建立推荐关系
            logger.error("recommend is exist in database table 'recommend',can't repeat save");
            throw new IllegalArgumentException("您已绑定推荐关系，不可重复绑定");
        }
        return memberOrg;
    }

}